package managedbeans;

import entities.Forumblocks;
import entities.Forumposts;
import entities.Forumthreads;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import utils.dataaccess.DBInterface;

@ManagedBean(name="forumBlocksBean")
@SessionScoped
public class ForumBlocksBean extends GenericForumBean{


    private ArrayList<Forumblocks> blocks;
    
    public ForumBlocksBean() {
         blocks = DBInterface.getBlocks();
         DBInterface.updateEventCounter();
    }

   public String showBlock(Forumblocks block){
         setCurrentBlock(block);
         return "/threads.xhtml?faces-redirect=true";
    }

       public int getPostsNumber(Forumblocks block){
        int postsNumber = 0;
        ArrayList<Forumthreads> threads = DBInterface.getBlocksThreads(block);
        for(Forumthreads thread : threads){
            postsNumber += DBInterface.getPosts(thread).size();
        }
        return postsNumber;
    }

    public int getThreadsNumber(Forumblocks block){
        return DBInterface.getBlocksThreads(block).size();
    }

    public ArrayList<Forumblocks> getBlocks() {
        return DBInterface.getBlocks();
    }

    public void setBlocks(ArrayList<Forumblocks> blocks) {
        this.blocks = blocks;
    }
    
    public void removeBlock(Forumblocks block){
        ArrayList<Forumthreads> threads = DBInterface.getBlocksThreads(block);
        for(Forumthreads thread : threads){
            removeThread(thread);
        }
        DBInterface.delete(block);
    }
    
    private void removeThread(Forumthreads thread){
        ArrayList<Forumposts> posts = DBInterface.getPosts(thread);
        for(Forumposts post : posts){
            DBInterface.delete(post);
        }
        DBInterface.delete(thread);
    }

}
